/*
 * Copyright (c) 2024.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.server.starter.exploiter.service.impl;

import com.server.starter.exploiter.domain.Script;
import com.server.starter.exploiter.repository.ScriptRepository;
import com.server.starter.exploiter.service.ScriptService;
import com.server.starter.exploiter.vo.ScriptVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ScriptServiceImpl implements ScriptService {

    private final ScriptRepository scriptRepository;

    public ScriptServiceImpl(ScriptRepository scriptRepository) {
        this.scriptRepository = scriptRepository;
    }

    @Override
    public List<ScriptVO> retrieve(String name) {
        if (StringUtils.hasText(name)) {
            return scriptRepository.findAllByNameContaining(name).stream().map(this::convert).toList();
        }
        return scriptRepository.findAll().stream().map(this::convert).toList();
    }

    @Override
    public ScriptVO fetch(Long id) {
        return scriptRepository.findById(id).map(this::convert).orElse(null);
    }

    /**
     * 类型转换
     *
     * @param script 信息
     * @return VO 输出对象
     */
    private ScriptVO convert(Script script) {
        ScriptVO vo = convert(script, ScriptVO.class);
        vo.setLastModifiedDate(script.getLastModifiedDate().orElse(null));
        return vo;
    }
}
